package com.fh.alipay.service.impl;

import cn.hutool.core.util.IdUtil;
import com.fh.alipay.po.GoodsImg;
import com.fh.alipay.mapper.GoodsImgMapper;
import com.fh.alipay.service.IGoodsImgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fh.alipay.utils.FileCommonUtil;
import com.fh.alipay.vo.ApiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.alipay.model.dto.GoodsImgDTO;
import com.fh.alipay.model.vo.GoodsImgVO;
import com.fh.alipay.model.query.GoodsImgQuery;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author fh
 * @date 2022-05-03
 * @description 商品图片表 服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodsImgServiceImpl extends ServiceImpl<GoodsImgMapper, GoodsImg> implements IGoodsImgService {

    @Value("${lqi.imgAddress}")
    private String imgAddress;

    @Value("${lqi.imgUrl}")
    private String imgUrl;

    @Override
    public IPage<GoodsImg> getWithPage(Page page, GoodsImgQuery query) {
        return baseMapper.getWithPage(page, query);
    }

    @Override
    public GoodsImg getOneByQuery(GoodsImgQuery query) {
        return baseMapper.getOneByQuery(query);
    }

    @Override
    public List<GoodsImg> getAllByQuery(GoodsImgQuery query) {
        return baseMapper.getAllByQuery(query);
    }

    @Override
    public ApiResult add(MultipartFile imgFile) {
        GoodsImg po = new GoodsImg();
        if (!imgFile.isEmpty()) {
            File file = FileCommonUtil.transferToFile(imgFile);
            boolean b = checkPic(file);
            if (!b) {
                FileCommonUtil.deleteFile(file);
                return ApiResult.error("图片不符合规范");
            }
            String originalFilename = imgFile.getOriginalFilename();
            po.setGoodsImgName(originalFilename);
            String type = getImgType(imgFile);
            //生成新文件名字
            String newFileName = getNewFileName();
            if ("jpg".equals(type) || "jpeg".equals(type) || "png".equals(type)) {
                po.setGoodsImgRealName(newFileName);
                // 封装上传文件位置的全路径 顶部图片上传
                File targetFile = new File(imgAddress, newFileName + ".png");
                //把本地文件上传到封装上传文件位置的全路径
                try {
                    imgFile.transferTo(targetFile);
                } catch (IOException e) {
                    FileCommonUtil.deleteFile(file, targetFile);
                    log.error("topFile.transferTo(targetFile) error：" + e);
                    return ApiResult.error("图片上传失败");
                }
                po.setCreateTime(LocalDateTime.now());
                po.setUpdateTime(LocalDateTime.now());
                po.setGoodsImgUrl(imgUrl + "/" + newFileName + ".png");
                baseMapper.insert(po);
                FileCommonUtil.deleteFile(file);
                return ApiResult.ok(po);
            }
        }
        return ApiResult.error("图片为空");
    }


    /**
     * 校验图片文件
     *
     * @param file
     * @return
     */
    private boolean checkPic(File file) {
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (IOException e) {
            log.error("checkPic error：" + e);
        }
        return bi != null;
    }

    private String getImgType(MultipartFile multipartFile) {
        //获取原始图片的拓展名
        String originalFilename = multipartFile.getOriginalFilename();
        assert originalFilename != null;
        int index = originalFilename.lastIndexOf('.') + 1;//获取地址.的前面的数字，从0开始
        return originalFilename.substring(index);//从地址.开始截取后缀
    }

    /**
     * 设置新的文件名
     *
     * @return
     */
    private String getNewFileName() {
        return IdUtil.simpleUUID();
    }
}
